/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};
class Solution
{
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
    {
        int aLen = 0,bLen = 0;
        ListNode* nodeA = headA;
        ListNode* nodeB = headB;
        while (nodeA!=nullptr)
        {
            aLen ++;
            nodeA = nodeA->next;
        }
        while (nodeB!= nullptr)
        {
            bLen ++;
            nodeB = nodeB->next;
        }
        if(aLen > bLen){
            nodeA = headA;
            headA = headB;
            headB = nodeA;
            int temp = aLen;
            aLen = bLen;
            bLen = temp;
        }
        //a < b
        nodeA = headA;
        nodeB = headB;
        for (int i = 0; i < bLen - aLen; i++)
        {
            nodeB = nodeB->next;
        }
        while (nodeA!=nullptr)
        {
            if(nodeA == nodeB){
                return nodeA;
            }else{
                nodeA = nodeA->next;
                nodeB = nodeB->next;
            }
        }
        return nullptr;
        
    }
};